package com.cqsxxy.service.impl;

import com.cqsxxy.pojo.User;
import com.cqsxxy.dao.UserMapper;
import com.cqsxxy.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cqsxxy.util.MdFive;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author rock
 * @since 2021-12-24
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public HashMap<String, Object> shiro(User user) {
        HashMap<String,Object> map = new HashMap<>();
        try {
            //1 用户令牌(用户和密码对象)
            UsernamePasswordToken token = new UsernamePasswordToken(user.getSysName(),user.getSysPwd());
            //2 创建shiro的用户对象
            Subject su = SecurityUtils.getSubject();
            //3 登录
            su.login(token);
            map.put("info","登录成功");
        }catch (UnknownAccountException u){
            u.printStackTrace();
            map.put("info","用户名不正确");
            System.out.println("用户名不正确");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            map.put("info","密码不正确");
            System.out.println("密码不正确");
        }
        return map;
    }

    @Override
    public HashMap<String, Object> register(User user) {
        HashMap<String,Object> map = new HashMap<>();
        //通过用户名查询是否有相同的用户
        List<User> userList = userMapper.selectByName(user.getSysName());
        //判断是由有相同的用户名
        if(userList.size()>0){
            map.put("info","用户名已存在");
            return map;
        }
        //用户名不存在
        //通过工具类MdFive对用户,盐值通过uuid进行获取
        user.setSalt(UUID.randomUUID().toString());     //通过uuid获得盐值
        //加密密码
        user.setSysPwd(new MdFive().encrypt(user.getSysPwd(),user.getSalt()));     //通过MDFive工具类,加密密码,加密不可逆
        //插入数据库
        int insert = userMapper.insert(user);
        if (insert>0){
            map.put("info","注册成功");
        }else {
            map.put("info","注册失败");
        }
        return map;
    }
}
